#!/bin/bash

NAME=cx-wool
LOG_HTM=/www/cx-wool.htm

usage() {
    cat <<-EOF
		Usage: app.sh [options]
		Valid options are:

		    -r                      run
			-w                      启动容器
		    -x                      更新镜像 
		    -y                      停止容器
		    -z                      重启容器
		    -h                      help
EOF
    exit $1
}

uci_get_by_name() {
    local ret=$(uci get $NAME.$1.$2 2>/dev/null)
    echo ${ret:=$3}
}

uci_get_by_type() {
    local ret=$(uci get $NAME.@$1[0].$2 2>/dev/null)
    echo ${ret:=$3}
}

uci_get_by_type2() {
	local index=0
	if [ -n $4 ]; then
	
		index=$4
	fi
	local ret=$(uci get $NAME.@$1[$index].$2 2>/dev/null)
	echo ${ret:=$3}
}

uci_set_by_type() {
	uci add_list $NAME.@$1[0].$2=$3 2>/dev/null
	uci commit $NAME
}

uci_dellist_by_type() {
	uci delete $NAME.@$1[0].$2 2>/dev/null
	uci commit $NAME
}

cancel() {
    if [ $# -gt 0 ]; then
        echo "$1"
    fi
    exit 1
}

jd_dir2=$(uci_get_by_type global jd_dir /opt/jdc)

a_run() {
	if [ ! -d $jd_dir2 ]; then
		echo "创建脚本目录..." >>$LOG_HTM 2>&1
		mkdir $jd_dir2
		chmod -R 777 $jd_dir2
    else
		echo "停止并删除容器..." >>$LOG_HTM 2>&1
		cd $jd_dir2
		docker-compose down >>$LOG_HTM 2>&1
		rm -rf $jd_dir2
		echo "容器已停止并删除" >>$LOG_HTM 2>&1
    fi
}

b_run() {
	mkdir $jd_dir2
    cd $jd_dir2
    echo "配置脚本参数..." >>$LOG_HTM 2>&1	
	cat <<-EOF > $jd_dir2/docker-compose.yml
version: "3.7"
services:
	EOF
	echo "下载脚本文件都/tmp目录..." >>$LOG_HTM 2>&1
	wget --no-check-certificate https://gitee.com/evine/jd-base/raw/v3/sample/config.sh.sample -O /tmp/config.sh.sample
	sleep 1
	wget --no-check-certificate https://gitee.com/evine/jd-base/raw/v3/sample/docker.list.sample -O /tmp/docker.list.sample
	sleep 1
	wget --no-check-certificate https://gitee.com/bkye/blc/raw/dev/diy.sh -O /tmp/diy.sh.sample

	local icount=$(uci show cx-wool | grep 'cookie_docker' | wc -l)
    let icount=icount-1
	for i in $(seq 0 $icount)
	do
		local cookie=$(uci_get_by_type2 docker_conf cookie_docker '' $i)
		local jd_cname=$(uci_get_by_type2 docker_conf jd_cname '' $i)
		local cont_men=$(uci_get_by_type2 docker_conf cont_men '' $i)
		local jd_image=$(uci_get_by_type2 docker_conf jd_image '' $i)
		local jd_push=$(uci_get_by_type2 docker_conf jd_push '' $i)
		echo "创建容器目录并复制配置文件..." >>$LOG_HTM 2>&1
		mkdir -p $jd_cname/config
		mkdir -p $jd_cname/scripts

	cp -R /tmp/config.sh.sample $jd_cname/config/config.sh
	cp -R /tmp/docker.list.sample $jd_cname/config/crontab.list
	cp -R /tmp/diy.sh.sample $jd_cname/config/diy.sh
	chmod 777 $jd_cname/config/diy.sh
	sed -i 's/^Cookie1=.*$/Cookie1=\"'$cookie'"/g' $jd_cname/config/config.sh
	echo "写入cookies到容器$jd_cname的配置文件" >>$LOG_HTM 2>&1
	config_build $jd_cname $jd_push
		cat <<-EOF >> $jd_dir2/docker-compose.yml
    $jd_cname:
      image: $jd_image
      deploy:
        resources:
          limits:
            memory: $cont_men
      container_name: $jd_cname
      restart: always
      network_mode: "host"
      extra_hosts:
        - "api.turinglabs.net:119.28.24.129"
      volumes:
        - ./$jd_cname/config:/jd/config
        - ./$jd_cname/log:/jd/log
        - ./$jd_cname/scripts:/jd/scripts
        - /etc/localtime:/etc/localtime
      tty: true
      environment:
        - ENABLE_WEB_PANEL=false
		EOF
	done
	rm -f /tmp/config.sh.sample
	rm -f /tmp/docker.list.sample
	rm -f /tmp/diy.sh.sample
}

config_build() {
	sed -i 's/^export PUSH_KEY=.*$/export PUSH_KEY=\""/g' $jd_dir2/$1/config/config.sh
	sed -i 's/^export BARK_PUSH=.*$/export BARK_PUSH=\""/g' $jd_dir2/$1/config/config.sh
	sed -i 's/^export BARK_SOUND=.*$/export BARK_SOUND=\""/g' $jd_dir2/$1/config/config.sh
	sed -i 's/^export TG_BOT_TOKEN=.*$/export TG_BOT_TOKEN=\""/g' $jd_dir2/$1/config/config.sh
	sed -i 's/^export TG_USER_ID=.*$/export TG_USER_ID=\""/g' $jd_dir2/$1/config/config.sh
	sed -i 's/^export DD_BOT_TOKEN=.*$/export DD_BOT_TOKEN=\""/g' $jd_dir2/$1/config/config.sh
	sed -i 's/^export DD_BOT_SECRET=.*$/export DD_BOT_SECRET=\""/g' $jd_dir2/$1/config/config.sh
	sed -i 's/^export IGOT_PUSH_KEY=.*$/export IGOT_PUSH_KEY=\""/g' $jd_dir2/$1/config/config.sh
	sed -i 's/^export PUSH_PLUS_TOKEN=.*$/export PUSH_PLUS_TOKEN=\""/g' $jd_dir2/$1/config/config.sh
	sed -i 's/^export PUSH_PLUS_USER=.*$/export PUSH_PLUS_USER=\""/g' $jd_dir2/$1/config/config.sh
	sed -i 's/^export QYWX_KEY=.*$/export QYWX_KEY=\""/g' $jd_dir2/$1/config/config.sh
	sed -i 's/^export QYWX_AM=.*$/export QYWX_AM=\""/g' $jd_dir2/$1/config/config.sh
	sed -i 's/.*export TG_PROXY_HOST=.*$/# export TG_PROXY_HOST=""/g' $jd_dir2/$1/config/config.sh
	sed -i 's/.*export TG_PROXY_PORT=.*$/# export TG_PROXY_PORT=""/g' $jd_dir2/$1/config/config.sh
	if [ $2 == "1" ]; then
	local push_mode="$(uci -q get cx-wool.@global[0].plus_msg)"
	for pushs in $push_mode
	do
		case "$pushs" in
			ServerChan)
				sed -i 's/^export PUSH_KEY=.*$/export PUSH_KEY=\"'$(uci_get_by_type global SCKEY)'"/g' $jd_dir2/$1/config/config.sh
			;;
			BARK)
				sed -i 's/^export BARK_PUSH=.*$/export BARK_PUSH=\"'$(uci_get_by_type global BARK_PUSH)'"/g' $jd_dir2/$1/config/config.sh
				sed -i 's/^export BARK_SOUND=.*$/export BARK_SOUND=\"'$(uci_get_by_type global BARK_SOUND)'"/g' $jd_dir2/$1/config/config.sh
			;;
			Telegram)
				sed -i 's/^export TG_BOT_TOKEN=.*$/export TG_BOT_TOKEN=\"'$(uci_get_by_type global TG_BOT_TOKEN)'"/g' $jd_dir2/$1/config/config.sh
				sed -i 's/^export TG_USER_ID=.*$/export TG_USER_ID=\"'$(uci_get_by_type global TG_USER_ID)'"/g' $jd_dir2/$1/config/config.sh
				if [ $(uci_get_by_type global TG_proxy) -eq 1 ];then
					sed -i 's/.*export TG_PROXY_HOST=.*$/export TG_PROXY_HOST="'$(uci_get_by_type global TG_PROXY_HOST)'"/g' $jd_dir2/$1/config/config.sh
					sed -i 's/.*export TG_PROXY_PORT=.*$/export TG_PROXY_PORT="'$(uci_get_by_type global TG_PROXY_PORT)'"/g' $jd_dir2/$1/config/config.sh
				fi
			;;
			DD)
				sed -i 's/^export DD_BOT_TOKEN=.*$/export DD_BOT_TOKEN=\"'$(uci_get_by_type global DD_BOT_TOKEN)'"/g' $jd_dir2/$1/config/config.sh
				sed -i 's/^export DD_BOT_SECRET=.*$/export DD_BOT_SECRET=\"'$(uci_get_by_type global DD_BOT_SECRET)'"/g' $jd_dir2/$1/config/config.sh
			;;
			iGot)
				sed -i 's/^export IGOT_PUSH_KEY=.*$/export IGOT_PUSH_KEY=\"'$(uci_get_by_type global IGOT_PUSH_KEY)'"/g' $jd_dir2/$1/config/config.sh
			;;
			PUSHP)
				sed -i 's/^export PUSH_PLUS_TOKEN=.*$/export PUSH_PLUS_TOKEN=\"'$(uci_get_by_type global PUSH_PLUS_TOKEN)'"/g' $jd_dir2/$1/config/config.sh
				sed -i 's/^export PUSH_PLUS_USER=.*$/export PUSH_PLUS_USER=\"'$(uci_get_by_type global PUSH_PLUS_USER)'"/g' $jd_dir2/$1/config/config.sh
			;;
			qywx)
				sed -i 's/^export QYWX_KEY=.*$/export QYWX_KEY=\"'$(uci_get_by_type global QYWX_KEY)'"/g' $jd_dir2/$1/config/config.sh
			;;
			qywxam)
				sed -i 's/^export QYWX_AM=.*$/export QYWX_AM=\"'$(uci_get_by_type global QYWX_AM)'"/g' $jd_dir2/$1/config/config.sh
			;;
		esac
	done
	fi
	#sed -i 's/^export QQ_SKEY=.*$/export QQ_SKEY=\"'$(uci_get_by_type global coolpush)'"/g' $jd_cname/config/config.sh
	#sed -i 's/^export QQ_MODE=.*$/export QQ_MODE=\"'$(uci_get_by_type global coolpush_mode)'"/g' $jd_cname/config/config.sh
	sed -i 's/^RandomDelay=.*$/RandomDelay="'$(uci_get_by_type global rdelay)'"/g' $jd_dir2/$1/config/config.sh
	sed -i 's/^NotifyBeanSign=.*$/NotifyBeanSign="'$(uci_get_by_type global notify_enable)'"/g' $jd_dir2/$1/config/config.sh
	sed -i 's/^export JD_BEAN_STOP=.*$/export JD_BEAN_STOP="'$(uci_get_by_type global beansignstop)'"/g' $jd_dir2/$1/config/config.sh
	sed -i 's/^EnableExtraShell=.*$/EnableExtraShell=\"true"/g' $jd_dir2/$1/config/config.sh
}

w_run() {
    echo "启动容器..." >>$LOG_HTM 2>&1
    jd_dir2=$(uci_get_by_type global jd_dir)
    cd $jd_dir2
    docker-compose --compatibility up -d >>$LOG_HTM 2>&1
}

x_run() {
    echo "更新镜像..." >>$LOG_HTM 2>&1
    jd_dir2=$(uci_get_by_type global jd_dir)
    cd $jd_dir2
    docker-compose --compatibility pull >>$LOG_HTM 2>&1
    echo "任务已完成" >>$LOG_HTM 2>&1
}

y_run() {
    echo "停止容器..." >>$LOG_HTM 2>&1
    jd_dir2=$(uci_get_by_type global jd_dir)
    cd $jd_dir2
    docker-compose --compatibility stop >>$LOG_HTM 2>&1
    echo "任务已完成" >>$LOG_HTM 2>&1
}

z_run() {
    echo "重启容器..." >>$LOG_HTM 2>&1
    jd_dir2=$(uci_get_by_type global jd_dir)
    cd $jd_dir2
    docker-compose --compatibility restart >>$LOG_HTM 2>&1
	echo "任务已完成" >>$LOG_HTM 2>&1
}

bb_run() {
	jd_cname=$(uci_get_by_type global jd_cname jd_c)
	sleep 2
	echo "等待两秒..." >>$LOG_HTM 2>&1
	local icount=$(uci show cx-wool | grep 'cookie_docker' | wc -l)
    let icount=icount-1
	for i in $(seq 0 $icount)
	do
		local jd_cname=$(uci_get_by_type2 docker_conf jd_cname '' $i)
		docker exec -i $jd_cname bash git_pull &
	done
}

u_run() {
	echo "更新diy脚本..." >>$LOG_HTM 2>&1
	j=1
	cd $jd_dir2
	wget --no-check-certificate https://gitee.com/bkye/blc/raw/dev/diy.sh -O /tmp/diy.sh
	local icount=$(uci show cx-wool | grep 'cookie_docker' | wc -l)
    let icount=icount-1
	for i in $(seq 0 $icount)
	do
	local jd_cname=$(uci_get_by_type2 docker_conf jd_cname '' $i)
	cp -r /tmp/diy.sh $jd_cname/config/diy.sh
	sleep 1
	docker exec -i $jd_cname bash git_pull
	done
}

s_run() {
	if [ -d $jd_dir2 ]; then
	local icount=$(uci show cx-wool | grep 'cookie_docker' | wc -l)
    let icount=icount-1
	for i in $(seq 0 $icount)
	do
	local jd_cname=$(uci_get_by_type2 docker_conf jd_cname '' $i)
	local jd_push=$(uci_get_by_type2 docker_conf jd_push '' $i)
	local cookie=$(uci_get_by_type2 docker_conf cookie_docker '' $i)
	sed -i 's/^Cookie1=.*$/Cookie1=\"'$cookie'"/g' $jd_dir2/$jd_cname/config/config.sh
	config_build $jd_cname $jd_push
	done
	fi
}

#互助码提取
allshare_code(){
	#清除旧的助力码
	uci_dellist_by_type global jxgc_sharecode
	uci_dellist_by_type global ddgc_sharecode
	uci_dellist_by_type global zddd_sharecode
	uci_dellist_by_type global nc_sharecode
	uci_dellist_by_type global pet_sharecode
	uci_dellist_by_type global jdzzsc_sharecode
	uci_dellist_by_type global czjsc_sharecode
	jd_dir2=$(uci_get_by_type global jd_dir)
	local icount=$(uci show cx-wool | grep 'cookie_docker' | wc -l)
    let icount=icount-1
	for i in $(seq 0 $icount)
	do
	local jd_cname=$(uci_get_by_type2 docker_conf jd_cname '' $i)
	## 东东农场
		cd $jd_dir2/$jd_cname/log/jd_fruit
	  for log in $(ls -r)
	  do
		ncsc=$(grep "的东东农场好友互助码" ${log} | perl -pe "s|【京东账号\d+（(.+)）的东东农场好友互助码】(\w+)|\2|" | uniq)
		[ -n "$ncsc" ] && break
	  done

	## 东东萌宠
	  cd $jd_dir2/$jd_cname/log/jd_pet
	  for log in $(ls -r)
	  do
		petsc=$(grep "的东东萌宠好友互助码" ${log} | perl -pe "s|【京东账号\d+（(.+)）的东东萌宠好友互助码】(.+)|\2|" | uniq)
		[ -n "$petsc" ] && break
	  done

	## 种豆得豆
	  cd $jd_dir2/$jd_cname/log/jd_plantBean
	  for log in $(ls -r)
	  do
		zdsc=$(grep "的京东种豆得豆好友互助码" ${log} | perl -pe "s|【京东账号\d+（(.+)）的京东种豆得豆好友互助码】(.+)|\2|" | uniq)
		[ -n "$zdsc}" ] && break
	  done

	## 京喜工厂
	  cd $jd_dir2/$jd_cname/log/jd_dreamFactory
	  for log in $(ls -r)
	  do
		jxsc=$(grep "的京喜工厂好友互助码" ${log} | perl -pe "s|【京东账号\d+（(.+)）的京喜工厂好友互助码】(.+)|\2|" | uniq)
		[ -n "$jxsc" ] && break
	  done

	## 东东工厂
	  cd $jd_dir2/$jd_cname/log/jd_jdfactory
	  for log in $(ls -r)
	  do
		ddsc=$(grep "的东东工厂好友互助码" ${log} | perl -pe "s|【京东账号\d+（(.+)）的东东工厂好友互助码】(.+)|\2|" | uniq)
		[ -n "$ddsc" ] && break
	  done

	## 疯狂的JOY
	  cd $jd_dir2/$jd_cname/log/jd_crazy_joy
	  for log in $(ls -r)
	  do
		czjsc=$(grep "的crazyJoy任务好友互助码" ${log} | perl -pe "s|【京东账号\d+（(.+)）的crazyJoy任务好友互助码】(.+)|\2|" | uniq)
		[ -n "$czjsc" ] && break
	  done

	## 京东赚赚
	  cd $jd_dir2/$jd_cname/log/jd_jdzz
	  for log in $(ls -r)
	  do
		jdzzsc=$(grep "的京东赚赚好友互助码" ${log} | perl -pe "s|【京东账号\d+（(.+)）的京东赚赚好友互助码】(.+)|\2|" | uniq)
		[ -n "$jdzzsc" ] && break
	  done

			if test -n "$ddsc" ; then
				uci_set_by_type global ddgc_sharecode $ddsc
				echo "容器$jd_cname的东东工厂互助码:"$ddsc >> $LOG_HTM 2>&1
			fi
			if test -n "$jxsc" ; then
				uci_set_by_type global jxgc_sharecode $jxsc
				echo "容器$jd_cname的京喜工厂互助码:"$jxsc >> $LOG_HTM 2>&1
			fi
			if test -n "$zdsc" ; then
				uci_set_by_type global zddd_sharecode $zdsc
				echo "容器$jd_cname的京东种豆得豆互助码:"$zdsc >> $LOG_HTM 2>&1
			fi
			if test -n "$ncsc" ; then
				uci_set_by_type global nc_sharecode $ncsc
				echo "容器$jd_cname的东东农场互助码:"$ncsc >> $LOG_HTM 2>&1
			fi
			if test -n "$petsc" ; then
				uci_set_by_type global pet_sharecode $petsc
				echo "容器$jd_cname的东东萌宠互助码:"$petsc >> $LOG_HTM 2>&1
			fi
			if test -n "$jdzzsc" ; then
				uci_set_by_type global jdzzsc_sharecode $jdzzsc
				echo "容器$jd_cname的京东赚赚互助码:"$jdzzsc >> $LOG_HTM 2>&1
			fi
			if test -n "$czjsc" ; then
				uci_set_by_type global czjsc_sharecode $czjsc
				echo "容器$jd_cname的crazyJoy互助码:"$czjsc >> $LOG_HTM 2>&1
			fi
	done

}

c_run() {
    echo "更新config.sh脚本..." >>$LOG_HTM 2>&1
	cd $jd_dir2
	wget --no-check-certificate https://gitee.com/evine/jd-base/raw/v3/sample/config.sh.sample -O /tmp/config.sh.sample
	local icount=$(uci show cx-wool | grep 'cookie_docker' | wc -l)
    let icount=icount-1
	for i in $(seq 0 $icount)
	do
	local jd_cname=$(uci_get_by_type2 docker_conf jd_cname '' $i)
	cp -r /tmp/config.sh.sample $jd_cname/config/config.sh
	done
}

n_run() {
	echo "正在下载相关文件" >$LOG_HTM 2>&1
	wget --no-check-certificate https://gitee.com/bkye/blc/raw/dev/ver.txt -O /tmp/ver.txt
	if [[ ! -s "/tmp/ver.txt" ]]; then
		echo "文件下载失败,更新终止，请重试！" >>$LOG_HTM 2>&1
		echo "任务已完成" >>$LOG_HTM 2>&1
		exit 1
	fi
	new_ver=`cat /tmp/ver.txt`
	old_ver=`awk '/luci-app-cx-wool/{getline a;print a}' /usr/lib/opkg/status | sed -e 's/Version: //g'`
	if [ $new_ver == $old_ver ]; then
		echo "暂无最新版本,请稍后尝试！本地版本为:$old_ver" >>$LOG_HTM 2>&1
		echo "任务已完成" >>$LOG_HTM 2>&1
		exit 0
	fi

	echo "最新版本为:$new_ver" >>$LOG_HTM 2>&1
	echo "本地版本为:$new_ver" >>$LOG_HTM 2>&1
	echo "开始进行更新..." >>$LOG_HTM 2>&1

	wget --no-check-certificate https://gitee.com/bkye/blc/raw/dev/luci-app-cx-wool_${new_ver}_all.ipk -O /tmp/luci-app-cx-wool_${new_ver}_all.ipk
	if [[ ! -s /tmp/luci-app-cx-wool_${new_ver}_all.ipk ]]; then
		echo "文件下载失败,更新终止，请重试！" >>$LOG_HTM 2>&1
		echo "任务已完成" >>$LOG_HTM 2>&1
		rm -f /tmp/luci-app-cx-wool_${new_ver}_all.ipk
		exit 1
	fi
	echo "开始安装:luci-app-cx-wool_${new_ver}_all.ipk" >>$LOG_HTM 2>&1
	rm -rf /tmp/luci-modulecache
	rm -f /tmp/luci-indexcache
	echo `opkg install /tmp/luci-app-cx-wool_${new_ver}_all.ipk --force-downgrade` >>$LOG_HTM 2>&1
	c_new=`awk '/luci-app-cx-wool/{getline a;print a}' /usr/lib/opkg/status | sed -e 's/Version: //g'`
	echo "更新完成,目前版本为:$c_new" >>$LOG_HTM 2>&1
	echo "清理临时文件..." >>$LOG_HTM 2>&1
	rm -f /tmp/ver.txt
	rm -f /tmp/luci-app-cx-wool_${new_ver}_all.ipk
	echo "任务已完成" >>$LOG_HTM 2>&1
}

save() {
		sed -i '/create_share_codes/d' /etc/crontabs/root
		[ $(uci_get_by_type global sc_update 0) -eq 1 ] && echo '3 3,5 1,10,20 * * /usr/share/cx-wool/create_share_codes.sh' >>/etc/crontabs/root
}

system_time() {
time3=$(date "+%Y-%m-%d %H:%M:%S")
echo "系统时间：$time3" >$LOG_HTM 2>&1
}

while getopts ":acnurstwxyzh" arg; do
    case "$arg" in
	a)
		system_time
		a_run
		b_run
		w_run
		bb_run
		echo "任务已完成" >>$LOG_HTM 2>&1
        exit 0
        ;;
	c)
		system_time
		c_run
		s_run
		echo "任务已完成" >>$LOG_HTM 2>&1
        exit 0
        ;;
    n)
		system_time
		n_run
        exit 0
        ;;
	u)
		system_time
		u_run
		echo "任务已完成" >>$LOG_HTM 2>&1
        exit 0
        ;;
    r)
		system_time
		#a_run
		b_run
		w_run
		bb_run
		echo "任务已完成" >>$LOG_HTM 2>&1
        exit 0
        ;;
	s)
		system_time
		s_run
		save
        exit 0
        ;;
	t)
	    echo "开始提取助力码" >$LOG_HTM 2>&1
		allshare_code
		echo "助力码提取完毕" >>$LOG_HTM 2>&1
        exit 0
        ;;
    w)
		system_time
        a_run
		echo "任务已完成" >>$LOG_HTM 2>&1
        exit 0
        ;;
    x)
	    system_time
        x_run
        exit 0
        ;;
    y)
	    system_time
        y_run
        exit 0
        ;;	
    z)
	   system_time
	    z_run
        exit 0
        ;;
    h)
        usage 0
        ;;
    esac
done
